#include "ExLevel.h"
#include "ExD3DWidget.h"
#include "ExD3DThread.h"
#include "ExGameTimer.h"
#include "ExGameObject.h"
#include "ExCamera.h"

ExLevel::ExLevel(QWidget *parent, QRect LevelRect)
	: QObject(parent), FrameCount(0), TimeElapsed(0.0)
{
	//init D3DWidget
	D3DWidget = new ExD3DWidget(parent);
	D3DWidget->setGeometry(LevelRect);
	D3DWidget->InitDirect3D();

	//init Camera
	Camera = new ExCamera(this);

	//init GameObject

	//init GameTimer
	GameTimer = new ExGameTimer(this);
	GameTimer->Reset();

	//start render thread
	D3DThread = new ExD3DThread(this);
	connect(D3DThread, SIGNAL(RenderRun()), this, SLOT(RenderRun()));
	D3DThread->start();
}

ExLevel::~ExLevel()
{
	D3DThread->Stop();
	D3DThread->quit();
	D3DThread->wait();
	delete D3DThread;

	D3DWidget->close();
	delete D3DWidget;

	delete GameTimer;

	delete Camera;
}

void ExLevel::OnResize(QRect LevelRect)
{
	D3DWidget->setGeometry(LevelRect);
	D3DWidget->OnResize();
}

void ExLevel::CalculateFrameStats()
{
	//保存这一秒内有多少帧
	FrameCount++;

	if ((GameTimer->TotalTime() - TimeElapsed) >= 1.0f)
	{
		float Fps = (float)FrameCount; // fps = frameCnt / 1
		float Mspf = 1000.0f / Fps;

		QString StateInfo = QString().sprintf("MainHUD FPS[%d] Frame Time[%fms] FrameCnt[%d]", (int)Fps, Mspf, FrameCount);

		// Reset for next average.
		FrameCount = 0;
		TimeElapsed += 1.0f;
	}
}


void ExLevel::DrawScene()
{
	static float BlackRGBA[4] = { 0.0f, 0.0f, 0.0f, 1.0f };	// RGBA = (0,0,0,255)
	D3DWidget->GetD3dImmediateContext()->ClearRenderTargetView(D3DWidget->GetRenderTargetView(), BlackRGBA);
	D3DWidget->GetD3dImmediateContext()->ClearDepthStencilView(D3DWidget->GetDepthStencilView(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);

	//IDXGISwapChain::Present方法--前后台缓冲区交换并呈现
	HR(D3DWidget->GetSwapChain()->Present(0, 0));
}

void ExLevel::RenderRun()
{
	CalculateFrameStats();
	DrawScene();
}
